package com.zackeus.mvvm.api.interceptor;

import androidx.annotation.NonNull;

import com.zackeus.mvvm.api.annotation.Timeout;
import com.zackeus.common.utils.ObjectUtils;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Invocation;

/**
 * 超时控制拦截器
 * @name: AnnotationInterceptor
 * @author: zz
 * @date: 2022/8/29
 */
public class TimeoutInterceptor implements Interceptor  {

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        final Invocation tag = request.tag(Invocation.class);
        final Method method = tag != null ? tag.method() : null;
        final Timeout timeout = method != null ? method.getAnnotation(Timeout.class) : null;

        if (ObjectUtils.isNull(timeout)) {
            return chain.proceed(request);
        }

        /* 修改超时设置 */
        if (timeout.connect() > 0) {
            chain = chain.withConnectTimeout(timeout.connect(), TimeUnit.SECONDS);
        }
        if (timeout.read() > 0) {
            chain = chain.withReadTimeout(timeout.read(), TimeUnit.SECONDS);
        }
        if (timeout.write() > 0) {
            chain = chain.withWriteTimeout(timeout.write(), TimeUnit.SECONDS);
        }
        return chain.proceed(request);
    }
}
